package datalookin.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import datalookin.adapter.ChoosePlantAdapter;
import datalookin.adapter.ChooseType2Adapter;
import datalookin.adapter.HistoryPlantAdapter;
import datalookin.dto.WaterPlantDto;
import datalookin.network.GetPlantType;
import datalookin.network.GetWatetPlantData;
import inter.Delegate;
import model.WaterPlant;
import utils.CacheHelper;
import utils.TimeUtil;

/**
 * 历史水厂信息
 * Created by Administrator on 2016/3/12.
 */
public class HistoryPlantMonitorActivity extends UIHandler.BaseActivity {

//    Spinner spinner_loc;
//    ChooseStationAdapter chooseStationAdapter = new ChooseStationAdapter();
//    List<Stationnumposition> stations = new ArrayList<Stationnumposition>();

//    {
//        chooseStationAdapter.setStations(stations);
//    }

    private Button btn_back;
    Spinner spinner_type;
    List<String> typeArray = new ArrayList<String>();
    ChooseType2Adapter chooseTypeAdapter = new ChooseType2Adapter();

    {
        chooseTypeAdapter.setTypeArray(typeArray);
    }

    Spinner spinner_plant;
    private List<WaterPlant> waterPlants = new ArrayList<WaterPlant>();
    ChoosePlantAdapter choosePlantAdapter = new ChoosePlantAdapter();

    {
        choosePlantAdapter.setPlants(waterPlants);
    }

    Button btn_timeStart;
    Button btn_timeStop;

    Calendar calendar = Calendar.getInstance();
    String timeStart = TimeUtil.currentDate();
    String timeEnd = timeStart;
    int start_year = calendar.get(Calendar.YEAR), start_month = calendar.get(Calendar.MONTH), start_day = calendar.get(Calendar.DAY_OF_MONTH);
    int end_year = start_year, end_month = start_month, end_day = start_day;

    String selectId;
    String selectType;

    ListView lv_history;
    List<WaterPlantDto> waterPlantDtos = new ArrayList<WaterPlantDto>();
    HistoryPlantAdapter historyPlantAdapter = new HistoryPlantAdapter();
    {
        historyPlantAdapter.setWaterPlantDtos(waterPlantDtos);
    }

    WaterPlant selectedWaterPlant;
    GetWatetPlantData getWatetPlantData;


    Delegate getPlantTypes = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("["))return;
            List<String> names = JSON.parseArray(response,java.lang.String.class);
            CacheHelper preferenceHelper = new CacheHelper(HistoryPlantMonitorActivity.this);
            preferenceHelper.putString(CacheHelper.PLANTTYPE,"data",response);
            typeArray.clear();
            typeArray.addAll(names);
            chooseTypeAdapter.notifyDataSetChanged();
        }

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };
    GetPlantType getPlantType = new GetPlantType();
    {
        getPlantType.setDelegate(getPlantTypes);
    }



    // 获取选择中的值
    Delegate historyvalue = new Delegate()
    {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("[")) return;
            List<WaterPlantDto> waterPlantDtosTmp = JSON.parseArray(response,WaterPlantDto.class);
            waterPlantDtos.clear();
            waterPlantDtos.addAll(waterPlantDtosTmp);
            historyPlantAdapter.notifyDataSetChanged();
        }

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };



    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_timeStart) {
                // 日期选择器
                Calendar calendar = Calendar.getInstance();
                Dialog dialog;
                dialog = new DatePickerDialog(HistoryPlantMonitorActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String tmpDate = year + "/" + (((monthOfYear + 1) <= 9 && (monthOfYear + 1) >= 1) ? "0" + (monthOfYear + 1) : (1 + monthOfYear) + "") + "/" + ((dayOfMonth >= 1 && dayOfMonth <= 9) ? "0" + dayOfMonth : dayOfMonth + "");
                        timeStart = tmpDate;
                        start_year = year;
                        start_month = monthOfYear;
                        start_day = dayOfMonth;
                        btn_timeStart.setText(start_year + "年" + (start_month + 1) + "月" + start_day + "日");
                        getHistoryInfo();
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dialog.show();
            } else if (v == btn_timeStop) {
                // 日期选择器
                Calendar calendar = Calendar.getInstance();
                Dialog dialog;
                dialog = new DatePickerDialog(HistoryPlantMonitorActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String tmpDate = year + "/" + (((monthOfYear + 1) <= 9 && (monthOfYear + 1) >= 1) ? "0" + (monthOfYear + 1) : (monthOfYear + 1) + "") + "/" + ((dayOfMonth >= 1 && dayOfMonth <= 9) ? "0" + dayOfMonth : dayOfMonth + "");
                        timeEnd = tmpDate;
                        end_year = year;
                        end_month = monthOfYear;
                        end_day = dayOfMonth;
                        btn_timeStop.setText(end_year + "年" + (end_month + 1) + "月" + end_day + "日");
                        if (timeEnd.compareTo(timeStart) <= 0) {
                            Toast.makeText(HistoryPlantMonitorActivity.this, "结束时间应大于起始时间", Toast.LENGTH_SHORT).show();
                        }
                        getHistoryInfo();
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dialog.show();
            }
            else if (v == btn_back)
            {
                HistoryPlantMonitorActivity.this.finish();
            }
        }
    };

    // 获取历史数据
    private void getHistoryInfo() {
        if (timeEnd == null || timeStart == null || selectType == null || selectedWaterPlant == null)return;
        getWatetPlantData = new GetWatetPlantData(historyvalue,selectedWaterPlant.getWaterPlantCode(),selectType,timeStart,timeEnd);
        getWatetPlantData.get();

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_planthistory);
        initview();
        initdata();
    }

    // 初始化数据
    private void initdata() {
        CacheHelper preferenceHelper = new CacheHelper(HistoryPlantMonitorActivity.this);

        if (preferenceHelper.contains(CacheHelper.PLANTTYPE, "data")) {
            String str = preferenceHelper.getString(CacheHelper.PLANTTYPE, "data");
            List<String> commontypes = JSON.parseArray(str, String.class);
            typeArray.addAll(commontypes);
            chooseTypeAdapter.notifyDataSetChanged();
        }

        if (preferenceHelper.contains(CacheHelper.ALLWATERPLANT, "data")) {
            List<WaterPlant> waterPlantsTmp = JSON.parseArray(
                    preferenceHelper.getString(CacheHelper.ALLWATERPLANT, "data"), WaterPlant.class);
            waterPlants.addAll(waterPlantsTmp);
            choosePlantAdapter.notifyDataSetChanged();
        }

        getPlantType.get();

    }

    // 初始化界面
    private void initview() {
//        spinner_loc = (Spinner) findViewById(R.id.id_spinner_loc);
//        spinner_loc.setAdapter(chooseStationAdapter);
//
//        spinner_loc.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
////                Stationnumposition stationnumposition = stations.get(position);
////                selectId = stationnumposition.getStationnum();
////                getHistoryInfo();
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });


        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(onClickListener);
        spinner_plant = (Spinner) findViewById(R.id.id_spinner_plant);
        spinner_plant.setAdapter(choosePlantAdapter);
        spinner_plant.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                WaterPlant waterPlant = (WaterPlant) view.getTag();
                onchoosePlant(waterPlant);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        spinner_type = (Spinner) findViewById(R.id.id_spinner_type);
        spinner_type.setAdapter(chooseTypeAdapter);
        spinner_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectType = typeArray.get(position);
                getHistoryInfo();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        btn_timeStart = (Button) findViewById(R.id.id_btn_timeBegin);
        btn_timeStart.setText(start_year + "年" + (start_month + 1) + "月" + start_day + "日");
        btn_timeStart.setOnClickListener(onClickListener);

        btn_timeStop = (Button) findViewById(R.id.id_btn_timeStop);
        btn_timeStop.setText(end_year + "年" + (end_month + 1) + "月" + end_day + "日");
        btn_timeStop.setOnClickListener(onClickListener);

        lv_history = (ListView) findViewById(R.id.id_lv_history);
        lv_history.setEmptyView(findViewById(R.id.id_v_nonemsg));
        lv_history.setAdapter(historyPlantAdapter);
    }

    // 选择中某水厂
    private void onchoosePlant(WaterPlant waterPlant) {
        selectedWaterPlant = waterPlant;
        getHistoryInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getWatetPlantData != null)
            getWatetPlantData.cancel();
    }
}

